package com.lucas.utils;



import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;

import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * @program: spring_cloud_lagou_homework
 * @author: lucasLu
 **/
public class CookiesUtil {

    /**
     * 增加cookies
     * @param key
     * @param value
     * @param response
     */
    public static void addCookies(String key, String value, HttpServletResponse response){
    if(StringUtils.isBlank(value)){
        return ;
    }
        ResponseCookie responseCookie = ResponseCookie.from(key,value)
                //禁止js读取
                .httpOnly(false)
                //secure用于在https传输协议上发送。故此处使用false,让http协议都能接受
                .secure(false)
                //域名,符合一下域名才发送cookies
                .domain("test.com")
                //URL路径上符合该格式才发送一下cookies
                .path("/")
                //1 小时过期
                .maxAge(Duration.ofHours(1))
                // 大多数情况也是不发送第三方 Cookie，但是导航到目标网址的 Get 请求除外
//                .sameSite("Lax")
                .build();

    response.setHeader(HttpHeaders.SET_COOKIE,responseCookie.toString());

    }

    public static void removeCookie(String key,HttpServletResponse response){
        ResponseCookie responseCookie =ResponseCookie.from(key,"")
                .domain("www.test.com")
                .path("/")
                .maxAge(0)
                .build();

        response.setHeader(HttpHeaders.SET_COOKIE,responseCookie.toString());
    }
}
